package ginx

import (
	"time"

	"gitee.com/iece/common/log"

	"github.com/gin-gonic/gin"
)

// Logger use logrus
func Logger(skipPaths ...string) gin.HandlerFunc {
	var skip map[string]struct{}

	if length := len(skipPaths); length > 0 {
		skip = make(map[string]struct{}, length)

		for _, path := range skipPaths {
			skip[path] = struct{}{}
		}
	}

	return func(c *gin.Context) {
		// Start timer
		start := time.Now()
		path := c.Request.URL.Path
		raw := c.Request.URL.RawQuery

		// Process request
		c.Next()

		// Log only when path is not being skipped
		if _, ok := skip[path]; !ok {
			param := gin.LogFormatterParams{
				Request: c.Request,
				Keys:    c.Keys,
			}

			// Stop timer
			param.TimeStamp = time.Now()
			param.Latency = param.TimeStamp.Sub(start)

			param.ClientIP = c.ClientIP()
			param.Method = c.Request.Method
			param.StatusCode = c.Writer.Status()
			param.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()

			param.BodySize = c.Writer.Size()

			if raw != "" {
				path = path + "?" + raw
			}

			param.Path = path

			log.Info(
				log.Field("common", "http"),
				log.Field("timeStamp", param.TimeStamp.Format(time.RFC3339)),
				log.Field("statusCode", param.StatusCode),
				log.Field("latency", param.Latency.String()),
				log.Field("clientIP", param.ClientIP),
				log.Field("method", param.Method),
				log.Field("path", param.Path),
				log.Field("errorMessage", param.ErrorMessage),
			)
		}
	}
}
